package edu.purdue.cs.cli;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;

import edu.purdue.cs.aggr.message.ControllerCommandMessage;

public class ControllerCommunicator
{
  public static String controllerIP;
  private static int port;
  private static ArrayList<String> nodes = new ArrayList<String>(31);

  private static void processArgs(String[] args)
  {
    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-port")) {
        port = Integer.parseInt(args[i + 1].trim());
        i++;
      }
      else if (args[i].equals("-controllerip")) {
        controllerIP = args[i + 1].trim();
        i++;
      }
      else {
        throw new IllegalArgumentException("Unknown parameter");
      }
    }
  }

  public static void main(String[] args)
  {
    processArgs(args);

    try {
      Socket socket = new Socket(controllerIP, port);
      ObjectOutputStream stream = new ObjectOutputStream(socket.getOutputStream());

      try {
        BufferedReader br = new BufferedReader(new FileReader("node-publicdns.txt"));
        String line;
        while ((line = br.readLine()) != null) {
          nodes.add(line);
        }
      }
      catch (Exception e) {
        // do nothing
      }

      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

      while (true) {
        String[] params = in.readLine().split(" ");
        if (params.length != 2)
          System.out.println("Usage: <command type> <node ID>");
        else {
          ControllerCommandMessage command = new ControllerCommandMessage();
          command.setType(params[0]);
          try {
            String[] indicies = params[1].split(",");
            String names = "";
            for (int i = 0; i < indicies.length; i++) {
              names += nodes.get(Integer.parseInt(indicies[i]));
              if (i < indicies.length - 1) names += ",";
            }
            command.setNodeId(names);
          }
          catch (NumberFormatException e) {
            command.setNodeId(params[1]);
          }
          stream.writeObject(command);
          stream.flush();
        }
      }

    }
    catch (UnknownHostException e) {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}
